package com.smart.web.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smart.model.Menu;
import com.smart.model.MenuCond;
import com.smart.util.CollectionUtil;
import com.smart.util.StringUtil;

@Controller
public class MenuController extends BaseController{
	@RequestMapping(value = "admin/menu/toList")
	public String listMenu(Long parentId, Model model){
		Menu parent = null;
		if(parentId==null){
			parent = menuService.findOneBy("code", Menu.ROOT_MENU_CODE);
			parentId = parent.getId();
		}
		else{
			parent = menuService.findOne(parentId);
		}
		MenuCond cond = new MenuCond();
		cond.setParentId(parentId);
		cond.addOrderByAsc("sort");
		List<Menu> list = menuService.find(cond);
		model.addAttribute("list", list);
		model.addAttribute("parent", parent);
		
		return "admin/menu/list";
	}
	
	@RequestMapping(value = "admin/menu/edit", method=RequestMethod.GET)
	public String preEditMenu(Long id, Long parentId, Model model) {
		if(id!=null){
			Menu menu = menuService.findOne(id);
			model.addAttribute("obj", menu);
		}
		else if(parentId!=null){
			// 添加子菜单
			Menu parent = menuService.findOne(parentId);
			Menu menu = new Menu();
			menu.setParent(parent);
			model.addAttribute("obj", menu);
		}
		return "admin/menu/edit";
	}
	
	@RequestMapping(value = "admin/menu/edit", method=RequestMethod.POST)
	public String editMenu(Menu form, Model model) {
		form.setUrl(StringUtil.isNotBlank(form.getUrl())?form.getUrl().trim() : "#");
		menuService.save(form);
		model.addAttribute("obj", form);
		setSuccessMsg(model);
		return "admin/menu/edit";
	}
	@RequestMapping(value = "admin/menu/edit2", method=RequestMethod.POST)
	public String editMenu2(Menu form, Model model) {
		if(form.getId()==null) {
			//新增根节点
			Menu entity=new Menu();
			if(form.getId()==null && form.getParentId()==null) {
				Menu parent = menuService.findOneBy("code", Menu.ROOT_MENU_CODE);
				entity.setParentId(parent.getId());
				entity.setLevel(parent.getLevel()+1);
			}else {//新增普通节点
				Menu parent = menuService.findOne(form.getParentId());
				entity.setParentId(parent.getId());
				entity.setLevel(parent.getLevel()+1);
			}
			entity.setName(form.getName());
			entity.setCode(form.getCode());
			entity.setUrl(StringUtil.isNotBlank(form.getUrl())?form.getUrl().trim() : "#");
			entity.setAttr1(form.getAttr1());
			entity.setAttr2(form.getAttr2());
			entity.setSort(form.getSort());
			menuService.save(entity);
		}else {
			Menu entity=menuService.findOne(form.getId());
			if(entity!=null) {
				entity.setName(form.getName());
				entity.setCode(form.getCode());
				entity.setUrl(StringUtil.isNotBlank(form.getUrl())?form.getUrl().trim() : "#");
				entity.setAttr1(form.getAttr1());
				entity.setAttr2(form.getAttr2());
				entity.setSort(form.getSort());
				menuService.save(entity);
			}
		}
		return "redirect:list";
	}
	
	@RequestMapping(value = "admin/menu/delete", method=RequestMethod.GET)
	public @ResponseBody String deleteMenu(Long id, HttpServletResponse response) {
		List<Menu> list = menuService.findBy("parentId", id);
		if(!CollectionUtil.isEmpty(list)){
			try {
				response.sendError(501);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		menuService.delete(id);
		return "OK";
	}
	
	
	@RequestMapping(value = "admin/menu/getInfo", method=RequestMethod.GET)
	public @ResponseBody Menu getInfo(Long id) {
		Menu menu=null;
		if(id!=null){
			menu= menuService.findOne(id);
		}
		return menu;
	}
	/**
	 * easyUI 加载菜单列表
	 * @param parentId
	 * @param model
	 * @return
	 */
	@RequestMapping("menu/initList")
	public @ResponseBody List<Menu> getList(Long parentId,Model model){
		//得到所有的菜单
		List<Menu> allList=menuService.findAll();
		List<Menu> resultList = new ArrayList<>();
		for (Menu menu : allList) {
			if (menu.getLevel()==0) {// 父级菜单开始添加
				resultList.add(menu);
			}
			if (ifChilds(allList, menu.getId())) {// 存在子集
				List<Menu> childs = new ArrayList<>();
				childs = getChild(menu.getId(), allList);
				menu.setChildren(childs);
			}
		}
		Menu parent = null;
		if (parentId == null) {
			parent = menuService.findOneBy("code", Menu.ROOT_MENU_CODE);
			parentId = parent.getId();
		} else {
			parent = menuService.findOne(parentId);
		}
		model.addAttribute("parent", parent);
		return resultList;
	}
	@RequestMapping(value = "admin/menu/list",method=RequestMethod.GET)
	public String getList1() {
		return "admin/menu/list";
	}
	
	
	/**
	 * 递归查找子菜单
	 * @param id 当前菜单id
	 * @param rootMenu 要查找的列表
	 * @return childs
	 */
	private List<Menu> getChild(Long id, List<Menu> rootMenu) {
		// 子菜单
		List<Menu> childList = new ArrayList<>();
		for (Menu menu : rootMenu) {
			// 遍历所有节点，将父菜单id与传过来的id比较
			if (menu.getParentId() != null) {
				if (menu.getParentId().equals(id)) {
					childList.add(menu);
				}
			}
		}
		// 把子菜单的子菜单再循环一遍
		for (Menu menu : childList) {// 子菜单还有子菜单
			// 递归
			menu.setChildren(getChild(menu.getId(), rootMenu));
		} // 递归退出条件
		if (childList.size() == 0) {
			return null;
		}
		return childList;
	}
	
	/**
	 * 是否存在直接子节点
	 * @param list
	 * @param pId
	 * @return
	 */
	private static boolean ifChilds(List<Menu> list, Long pId) {
		boolean flag = false;
		for (Menu menu : list) {
			if (menu.getParentId() != null && menu.getParentId().equals(pId)) {
				flag = true;
				break;
			}
		}
		return flag;
	}
}
